from flask import Flask, session, render_template, redirect, Blueprint, request
from db import db

from model.Users import Users
from model.History import History
from utils.errorResponse import errorResponse

user_bp = Blueprint('user', __name__, url_prefix='/user', template_folder='templates')


@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        print(request.form)
        user = Users.query.filter_by(name=request.form['username'], password=request.form['password']).first()
        print(user)
        if user:
            session['username'] = user.name
            return redirect('/page/home')
        else:
            return errorResponse('账号或密码不正确！')
        pass
    else:
        return render_template('login.html')


@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user = Users.query.filter_by(name=request.form['username']).first()
        if user:
            return errorResponse('该账号已被注册！')
        else:
            user = Users(name=request.form['username'], password=request.form['password'])
            db.session.add(user)
            db.session.commit()
            return redirect('/user/login')
        pass
    else:
        return render_template('register.html')


@user_bp.route('logOut', methods=['POST'])
def logOut():
    session.clear()
    return redirect('/user/login')

